package cn.hesion;
/**
 * ClassName: StateDemo <br/>
 * Description: <br/>
 * date: 2021/9/10 20:07<br/>
 *
 * @author Hesion<br />
 * @version
 * @since JDK 1.8
 */

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * State案例
 * @author: hesion
 * @create: 2021-09-10 20:07
 * //（1,3）（1,5）（1,7）（1,4）（1,2）
 *  * 利用state求平均值
 **/
public class StateDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.enableCheckpointing(2000);
        //从socket流接受数据
        final DataStreamSource<String> data = env.socketTextStream("114.96.84.47", 9999);

        SingleOutputStreamOperator<Tuple2<Long, Long>> maped = data.map(new MapFunction<String, Tuple2<Long, Long>>() {
            @Override
            public Tuple2<Long, Long> map(String s) throws Exception {
                String[] splited = s.split(",");
                return new Tuple2<Long, Long>(Long.valueOf(splited[0]), Long.valueOf(splited[1]));
            }
        });


        KeyedStream<Tuple2<Long, Long>, Long> keybyed = maped.keyBy(value -> value.f0);

        //根据key分组策略，对流式数据进行状态化处理
        SingleOutputStreamOperator<Tuple2<Long, Long>> flatMaped = keybyed.flatMap(new RichFlatMapFunction<Tuple2<Long, Long>, Tuple2<Long, Long>>() {
            ValueState<Tuple2<Long, Long>> sumState;

            @Override
            public void open(Configuration parameters) throws Exception {
                //在open方法中做出State
                ValueStateDescriptor<Tuple2<Long, Long>> descriptor = new ValueStateDescriptor<>(
                        "average",
                        TypeInformation.of(new TypeHint<Tuple2<Long, Long>>() {
                        }), Tuple2.of(0L, 0L));
                //获取当前的state
                sumState = getRuntimeContext().getState(descriptor);
                super.open(parameters);
            }

            @Override
            public void flatMap(Tuple2<Long, Long> longLongTuple2, Collector<Tuple2<Long, Long>> collector) throws Exception {
                Tuple2<Long, Long> currentSum = sumState.value();
                currentSum.f0 += 1;
                currentSum.f1 += longLongTuple2.f1;

                sumState.update(currentSum);


                if (currentSum.f0 == 5) {
                    long average = currentSum.f1 / currentSum.f0;
                    collector.collect(new Tuple2<>(longLongTuple2.f0, average));
                    sumState.clear();
                }
            }


        });

        flatMaped.print();
        env.execute();

    }
}
